<!-- src/App.vue -->
<template>
  <div id="app">
    <div v-if="loading" class="loading">正在登录中...</div>
    <div v-else-if="authError" class="auth-error">
      <h2>认证失败</h2>
      <p>{{ authError }}</p>
      <button @click="retryAuth">重试认证</button>
      <button @click="proceedWithoutAuth">继续访问（无认证模式）</button>
    </div>
    <router-view v-else />
  </div>
</template>

<!-- src/App.vue -->
<script>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { getToken, tokenRef } from '@/utils/auth'

export default {
  name: 'App',
  setup() {
    const loading = ref(true)
    const authError = ref('')
    const router = useRouter()

    // 修复：正确记录 token 变化
    watch(
      () => tokenRef.value,
      (newToken, oldToken) => { // 添加 oldToken 参数
        console.log('Token 变化:', {
          oldToken: oldToken ? '存在' : '不存在', // 显示真正的旧值
          newToken: newToken ? '存在' : '不存在', // 显示真正的新值
          loading: loading.value
        });

        if (newToken) {
          loading.value = false;
        }
      },
      { immediate: true }
    );

    // 或方式2：也可以继续用 getToken()，但本质是读取 tokenRef.value
    // watch(getToken, ...) 也可以工作

    const retryAuth = () => {
      authError.value = ''
      loading.value = true
      sessionStorage.removeItem('redirectAttempted')
    }

    const proceedWithoutAuth = () => {
      authError.value = ''
      loading.value = false
    }

    onMounted(() => {
      if (getToken()) {
        loading.value = false
      }
    })

    return {
      loading,
      authError,
      retryAuth,
      proceedWithoutAuth
    }
  }
}
</script>

<style>
.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  font-size: 18px;
}

.auth-error {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  padding: 20px;
  text-align: center;
}

.auth-error button {
  margin: 10px;
  padding: 10px 20px;
  background-color: #4285f4;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.auth-error button:hover {
  background-color: #3367d6;
}
</style>
